local lspinstall = require('lspinstall')
local lspconfig = require('lspconfig')
--local cmp_nvim_lsp = require('cmp_nvim_lsp')
local lsp_status = require('lsp-status')

local M = {}

local function on_attach(client, bufnr)
  -- 绑定快捷键
  require('my.keymap').lsp_mapping_on_attach(client, bufnr)
  -- status
  lsp_status.on_attach(client, bufnr)
end

local function make_config(server)
  -- capabilities
	local capabilities = vim.lsp.protocol.make_client_capabilities()
	-- TODO cmp snipts
	-- capabilities = cmp_nvim_lsp.update_capabilities(capabilities)
  -- status
  capabilities = vim.tbl_extend('keep', capabilities, lsp_status.capabilities)


	local config =  {
		capabilities = capabilities,
		-- lsp 启动后, 绑定快捷键
		on_attach = on_attach,
	}

	if server == "elixirls" then
		config.settings = {
			elixirLS = {
			  dialyzerEnabled = false,
			  fetchDeps = false,
			  enableTestLenses = true
			}
		}
	elseif server == "lua" then
		config.settings = {
      Lua = {
			runtime = {
				-- LuaJIT in the case of Neovim
				version = 'LuaJIT',
				path = vim.split(package.path, ';'),
			  },
			  diagnostics = {
				-- Get the language server to recognize the `vim` global
				globals = {'vim'},
			  },
			  workspace = {
				-- Make the server aware of Neovim runtime files
				library = {
				  [vim.fn.expand('$VIMRUNTIME/lua')] = true,
				  [vim.fn.expand('$VIMRUNTIME/lua/vim/lsp')] = true,
				},
			}
      }
		} end
	return config
end

local function setup_servers()
	local servers = lspinstall.installed_servers()
	for _, server in pairs(servers) do
		local config = make_config(server)
		lspconfig[server].setup(config)
	end
end

local function setup_saga()
  local saga = require('lspsaga')
  saga.init_lsp_saga{}
end

local function setup_trouble()
  local trouble = require("trouble")
  trouble.setup {}
end

M.setup = function()
  lspinstall.setup()
  lsp_status.register_progress()
  setup_servers()

  setup_saga()
  setup_trouble()

  -- 安装完成后重新加载
  lspinstall.post_install_hook = function ()
	  setup_servers()
	  vim.cmd("bufdo e")
  end

  if next(vim.lsp.buf_get_clients()) ~= nil then
    lsp_status.status()
  end
end

return M
